package com.jgy.controller;

import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.jgy.entity.Stu;
import com.jgy.poi.word.ZipUtils;
import com.jgy.utils.R;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author 姜光远
 * @date 2023/4/11 14:00
 */
@RestController
public class PoiExportController {

    /**
     * 模板路径
     */
    String templatePath = "E:/springcloud/space-pro/space-parent/study-model/src/main/resources/template/testpoi.docx";

    /**
     * 压缩zip路径
     */
    String templateZip = "E:/word/poi/export.zip";
    //生成的word路径
    String fileDir = "E:/word/";
    //生成的文件名字
    String fileName = "exportpoi1";

    @GetMapping(value = "/load")
    public R<Object> reload(HttpServletResponse response, HttpServletRequest request) throws FileNotFoundException {
        List<String> filePath = new ArrayList<>();
        HashMap<String, Object> exampleData = new HashMap<>(16);
        exampleData.put("myname", "admin");
        exampleData.put("myage", "123456");
        //要循环的数据
        ArrayList<Object> list = new ArrayList<>();
        for (int i = 0; i < 15; i++) {
            list.add(new Stu("老QI" + i, "2" + i,i+1));
        }
        exampleData.put("list", list);

        // 这里是行循环实例
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure config = Configure.builder()
                .bind("list", policy).build();

        //通过模板创建word文档
        ZipUtils.createWord(templatePath,fileDir,fileName,exampleData,config);
        String path = fileDir + fileName + ".docx";
        filePath.add(path);

        //将创建的word文档压缩成zip
        ZipUtils.createZip(templateZip, filePath);

        //下载zip
        ZipUtils.downLoadFile(templateZip,response);

        ZipUtils.delAllFile(fileDir);

        return R.ok();
    }
}
